﻿using Bootstrap.Security.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace Bootstrap.Security.Mvc.TagHelpers
{
    /// <summary>
    /// 网页控件授权帮助类
    /// </summary>
    [HtmlTargetElement(Attributes = "asp-auth", TagStructure = TagStructure.NormalOrSelfClosing)]
    public class AuthorizateTagHelper : TagHelper
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="authorization">IButtonAuthorization 实例</param>
        /// <param name="httpContextAccessor">IHttpContextAccessor 实例</param>
        public AuthorizateTagHelper(IButtonAuthorization authorization, IHttpContextAccessor httpContextAccessor)
        {
            AuthorizationServices = authorization;
            HttpContext = httpContextAccessor.HttpContext;
        }

        /// <summary>
        /// 获得 按钮授权服务
        /// </summary>
        public IButtonAuthorization AuthorizationServices { get; private set; }

        /// <summary>
        /// 获得 请求上线文
        /// </summary>
        public HttpContext HttpContext { get; private set; }

        /// <summary>
        /// 获得/设置 授权键值
        /// </summary>
        [HtmlAttributeName("asp-auth")]
        public string AuthKey { get; set; }

        /// <summary>
        /// HTML处理方法
        /// </summary>
        /// <param name="context">HTML Tag 上下文</param>
        /// <param name="output">Tag 内容流</param>
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (AuthorizationServices.Authorizate(HttpContext, $"~{HttpContext.Request.Path}", AuthKey))
            {
                // 授权通过生成相对应的 HTML 到上下文中
                base.Process(context, output);
                return;
            }

            // 授权未通过时不生成相对应的 HTML
            output.SuppressOutput();
        }
    }
}
